﻿using System.ComponentModel;
using Demo.Identity.Permissions.Dto;

namespace Demo.Permissions;

/// <summary>
/// 权限注册
/// </summary>
public static class PermissionRegistor
{

    /// <summary>
    /// 在指定类型中获取权限集合
    /// </summary>
    /// <param name="serviceName">服务名称</param>
    /// <typeparam name="T">类型</typeparam>
    /// <returns></returns>
    internal static List<SysPermissionDto> GetPermissions<T>(string serviceName)
    {
        List<SysPermissionDto> result = new List<SysPermissionDto>();
        Type type = typeof(T);
        var fields = type.GetFields().Where(x=>x.IsPublic&&x.IsStatic);
        foreach (var field in fields)
        {
            string code = field.GetValue(null).ToString();
            string name = "";
            object[] objs = field.GetCustomAttributes(typeof(DescriptionAttribute), false);  //获取描述属性
            if (objs != null && objs.Length > 0)
            {
                DescriptionAttribute descriptionAttribute = (DescriptionAttribute) objs[0];
                name = descriptionAttribute.Description;
            }

            string parentCode = null;
            if (code.Contains("."))
            {
                parentCode = code.Substring(0, code.LastIndexOf('.'));
            }

            result.Add(new SysPermissionDto()
            {
                Name = name,
                Code = code,
                ParentCode = parentCode,
                ServiceName = serviceName,
            });
        }

        return result;
    }
}